package com.csot.ry.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.BiMap;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import com.csot.common.exception.ServiceException;
import com.csot.model.CityIp;
import com.csot.model.CitySegment;
import com.csot.ry.domain.TCheckSegment;
import com.csot.ry.util.CacheKitUtil;
import com.csot.common.core.domain.entity.SysRole;
import com.csot.common.core.domain.entity.SysUser;
import com.csot.common.utils.DateUtils;
import com.csot.common.utils.SecurityUtils;
import com.csot.common.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.csot.ry.mapper.TCityIpMapper;
import com.csot.ry.domain.TCityIp;
import com.csot.ry.service.ITCityIpService;

/**
 * 地址ip明细Service业务层处理
 *
 * @author LS
 * @date 2022-05-31
 */
@Service
public class TCityIpServiceImpl implements ITCityIpService {
    @Autowired
    private TCityIpMapper tCityIpMapper;

    /**
     * 查询地址ip明细
     *
     * @param id 地址ip明细主键
     * @return 地址ip明细
     */
    @Override
    public TCityIp selectTCityIpById(Long id) {
        return tCityIpMapper.selectTCityIpById(id);
    }

    /**
     * 查询地址ip明细列表
     *
     * @param tCityIp 地址ip明细
     * @return 地址ip明细
     */
    @Override
//    @DataScope(deptAlias = "d")
    public List<TCityIp> selectTCityIpList(TCityIp tCityIp) {

        SysUser user = SecurityUtils.getLoginUser().getUser();

//        List<SysRole> roles = user.getRoles();
//        List<String> roleKeys = roles.stream()
//                .map(r -> {
//                    return "'" + r.getRoleKey() + "'";
//                }).collect(Collectors.toList());
//        String iptype = StringUtils.join(roleKeys, ",");
//        if (iptype.contains("admin")) {
//            if (StrUtil.isNotEmpty(tCityIp.getIpType())) {
//                tCityIp.setIpType("'" + tCityIp.getIpType() + "'");
//            }
//        } else if (StrUtil.isNotEmpty(tCityIp.getIpType())) {
//            if (!iptype.contains(tCityIp.getIpType())) {
//                throw new IllegalArgumentException("没有此网络类型的权限！");
//            } else {
//                tCityIp.setIpType("'" + tCityIp.getIpType() + "'");
//            }
//        } else {
//            tCityIp.setIpType(iptype);
//        }
        Long deptid = user.getDeptId();
        if (deptid != 100) {
            tCityIp.setIpCity(CacheKitUtil.ip_dept.get(user.getDept().getParentId() + ""));
        }

        try {
            if (StrUtil.isNotEmpty(tCityIp.getIpStart())) {
                tCityIp.setIpStartI(NetUtil.ipv4ToLong(tCityIp.getIpStart()));
            }
            if (StrUtil.isNotEmpty(tCityIp.getIpEnd())) {
                tCityIp.setIpEndI(NetUtil.ipv4ToLong(tCityIp.getIpEnd()));
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("起止IP不正确");
        }
        return tCityIpMapper.selectTCityIpList(tCityIp);
    }

    /**
     * 新增地址ip明细
     *
     * @param tCityIp 地址ip明细
     * @return 结果
     */
    @Override
    public int insertTCityIp(TCityIp tCityIp) {
        tCityIp.setCreateTime(DateUtils.getNowDate());
        return tCityIpMapper.insertTCityIp(tCityIp);
    }

    /**
     * 修改地址ip明细
     *
     * @param tCityIp 地址ip明细
     * @return 结果
     */
    @Override
    public int updateTCityIp(TCityIp tCityIp) {
        tCityIp.setUpdateTime(DateUtils.getNowDate());
        return tCityIpMapper.updateTCityIp(tCityIp);
    }

    /**
     * 批量删除地址ip明细
     *
     * @param ids 需要删除的地址ip明细主键
     * @return 结果
     */
    @Override
    public int deleteTCityIpByIds(Long[] ids) {
        return tCityIpMapper.deleteTCityIpByIds(ids);
    }

    /**
     * 删除地址ip明细信息
     *
     * @param id 地址ip明细主键
     * @return 结果
     */
    @Override
    public int deleteTCityIpById(Long id) {
        return tCityIpMapper.deleteTCityIpById(id);
    }

    private BiMap<String, String> ip_city = CacheKit.get("dict-data", "ip_city");
    private BiMap<String, String> ip_use_type = CacheKit.get("dict-data", "ip_use_type");

    /**
     * 查询城市ip列表
     *
     * @param tCityIps 城市ip列表
     * @return 城市ip段
     */
    @Override
    public List<TCityIp> TCityIpLists(List<TCityIp> tCityIps) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long deptid = user.getDeptId();
        Long pdeptid = deptid;
        if (deptid != 100) {
            pdeptid = user.getDept().getParentId();
        }
        String city_e = CacheKitUtil.ip_dept.get(String.valueOf(pdeptid));

        List<TCityIp> returnList = new ArrayList<>();
        List<CityIp> cityIpList = new ArrayList<>();
        Kv inoid = Kv.create().set("oid", tCityIps.stream().map(TCityIp::getIpAddress).collect(Collectors.toList()));
        inoid.set("city", city_e);
        if (deptid != 100) {
            cityIpList = new CityIp().dao().templateByString("select * from t_city_ip where ip_address in #para(oid,\"in\")  and ip_city = #para(city)", inoid).find();
        } else {
            cityIpList = new CityIp().dao().templateByString("select * from t_city_ip where ip_address in #para(oid,\"in\")  ", inoid).find();
        }
        cityIpList.stream().forEach(c -> {
            TCityIp tc = new TCityIp();
            BeanUtils.copyProperties(c, tc);
            returnList.add(tc);
        });
        return returnList;
    }
}
